﻿using BCCommon;
using BCCommon.TMS.Transport;
using BCData.TMS.Agent.AgentRecord;
using BCData.TMS.VehicleTransportBusinessConfig;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.VehicleTransportBusinessConfigOverwrite;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.VehicleTransportBusinessConfig;
using BCService.Common.Area;
using BCService.TMS.Agent.AgentAreaRecord;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.VehicleTransportBusinessConfigOverwrite
{
    public class VehicleTransportBusinessConfigOverwriteService : IVehicleTransportBusinessConfigOverwriteService
    {
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;
        private readonly IVehicleTransportBusinessConfigOverwriteData vehicleTransportBusinessConfigOverwriteData;
        private readonly IVehicleTransportBusinessConfigData vehicleTransportBusinessConfigData;
        private readonly IAgentRecordData agentRecordData;
        private readonly IAgentAreaRecordService agentAreaRecordService;
        private readonly string key = string.Format("{0}", EntityNameConst.VehicleTransportBusinessConfigOverwriteEntity);

        public VehicleTransportBusinessConfigOverwriteService(IRedisService redisService,
            IZoneService zoneService,
            IVehicleTransportBusinessConfigOverwriteData vehicleTransportBusinessConfigOverwriteData,
            IVehicleTransportBusinessConfigData vehicleTransportBusinessConfigData,
            IAgentRecordData agentRecordData,
            IAgentAreaRecordService agentAreaRecordService)
        {
            this.redisService = redisService;
            this.zoneService = zoneService;
            this.vehicleTransportBusinessConfigOverwriteData = vehicleTransportBusinessConfigOverwriteData;
            this.vehicleTransportBusinessConfigData = vehicleTransportBusinessConfigData;
            this.agentRecordData = agentRecordData;
            this.agentAreaRecordService = agentAreaRecordService;
        }

        public VehicleTransportBusinessConfigOverwriteDto Create(AdminDto admin, VehicleTransportBusinessConfigOverWriteRequestDto requestDto)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("只有代理商才可重写车辆运输业务配置");
            }
            var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
            if (agentRecord == null)
            {
                throw new ArgumentException("您不归属任何代理商，暂无权限修改");
            }
            if (string.IsNullOrWhiteSpace(requestDto.ProvinceCode) || string.IsNullOrWhiteSpace(requestDto.CityCode) || string.IsNullOrWhiteSpace(requestDto.CountyCode))
            {
                throw new ArgumentException("省市区信息不能为空");
            }
            var zoneEntity = this.zoneService.GetFromZoneEntity(requestDto.CountyCode);
            if (zoneEntity == null || zoneEntity.countyEntity == null)
            {
                throw new ArgumentException("区县编码不存在!");
            }
            if (!this.agentAreaRecordService.CheckCountyAuthorize(zoneEntity.countyEntity.CountyCode, agentRecord.AgentRecordId))
            {
                throw new ArgumentException("此区域授权失败!");
            }
            if (requestDto.VehicleTransportBusinessConfigId <= 0)
            {
                throw new ArgumentException("车辆运输业务配置Id不能为空");
            }
            var parentConfig = this.vehicleTransportBusinessConfigData.GetEntity(requestDto.VehicleTransportBusinessConfigId).Result;
            if (parentConfig == null)
            {
                throw new ArgumentException("车辆运输业务配置信息不存在");
            }
            var result = this.vehicleTransportBusinessConfigOverwriteData.GetEntity(agentRecord.AgentRecordId, requestDto.VehicleTransportBusinessConfigId, zoneEntity.provinceEntity.ProvinceCode, zoneEntity.cityEntity.CityCode, requestDto.CountyCode, parentConfig.TransportBusiness).Result;
            if (result == null)
            {
                result = this.vehicleTransportBusinessConfigOverwriteData.Insert(new VehicleTransportBusinessConfigOverwriteEntity()
                {
                    VehicleTransportBusinessConfigId = parentConfig.VehicleTransportBusinessConfigId,
                    TransportBusiness = parentConfig.TransportBusiness,
                    Enabled = true,
                    BusinessOrder = parentConfig.BusinessOrder,
                    Remark = parentConfig.Remark,
                    SameCityChargingMode = !string.IsNullOrWhiteSpace(parentConfig.SameCityChargingMode) ? parentConfig.SameCityChargingMode : null,
                    SameCityPointSurchargeAmount = parentConfig.SameCityPointSurchargeAmount,
                    ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                    CityCode = zoneEntity.cityEntity.CityCode,
                    CountyCode = requestDto.CountyCode,
                    AgentRecordId = agentRecord.AgentRecordId,
                    CreateAdminId = admin.AdminId,
                    CreateAdminName = admin.FullName,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    EditAdminId = admin.AdminId,
                    EditAdminName = admin.FullName
                }).GetAwaiter().GetResult();
                this.redisService.DeleteMultipleKey(key, false);
            }
            return result.As<VehicleTransportBusinessConfigOverwriteDto>();
        }

        public void Delete(AdminDto admin, int vehicleTransportBusinessConfigOverwriteId)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("非代理商无权删除此配置!");
            }
            var result = this.vehicleTransportBusinessConfigOverwriteData.GetEntity(vehicleTransportBusinessConfigOverwriteId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置重写信息不存在");
            }
            this.vehicleTransportBusinessConfigOverwriteData.DeleteByConfigOverwriteId(vehicleTransportBusinessConfigOverwriteId).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
        }

        public PageableList<VehicleTransportBusinessConfigOverwriteViewDto> Query(long? agentRecordId, TransportBusinessType? transportBusiness, string provinceCode, string cityCode, string countyCode, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, agentRecordId, transportBusiness, provinceCode, cityCode, countyCode, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (data, dataCount) = this.vehicleTransportBusinessConfigOverwriteData.Query(agentRecordId, transportBusiness, provinceCode, cityCode, countyCode, pageIndex, pageSize).Result;
                return new PageableList<VehicleTransportBusinessConfigOverwriteViewDto>()
                {
                    Count = dataCount,
                    Items = data.As<List<VehicleTransportBusinessConfigOverwriteViewDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
            }, TimeSpan.FromDays(1));
            return result;
        }

        public VehicleTransportBusinessConfigOverwriteDto Update(AdminDto admin, int vehicleTransportBusinessConfigOverwriteId, VehicleTransportBusinessConfigOverwritePutDto putDto)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("非代理商无权修改此配置!");
            }
            var result = this.vehicleTransportBusinessConfigOverwriteData.GetEntity(vehicleTransportBusinessConfigOverwriteId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置重写信息不存在");
            }
            if (result.AgentRecordId != admin.AgentRecord.AgentRecordId)
            {
                throw new ArgumentException("此记录不属于当前代理商，暂无权限修改");
            }
            if (result.TransportBusiness == TransportBusinessType.SameCity.ToString())
            {
                if (!putDto.SameCityChargingMode.HasValue)
                {
                    throw new ArgumentException("同城计费模式不允许为空!");
                }
                if(putDto.SameCityChargingMode.Value == TransportSameCityChargingMode.EveryPointSurchargeAmount&& !putDto.SameCityPointSurchargeAmount.HasValue)
                {
                    throw new ArgumentException("同城途经点串连计费模式时，同城途经点附加费金额为必填!");
                }
            }

            result.BusinessOrder = putDto.BusinessOrder;
            result.SameCityChargingMode = putDto.SameCityChargingMode.ToString();
            result.SameCityPointSurchargeAmount = putDto.SameCityPointSurchargeAmount;
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.vehicleTransportBusinessConfigOverwriteData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<VehicleTransportBusinessConfigOverwriteDto>();
        }

        public VehicleTransportBusinessConfigOverwriteDto UpdateEnabled(AdminDto admin, int vehicleTransportBusinessConfigOverwriteId, bool enabled)
        {
            if (admin.AgentRecord == null)
            {
                throw new ArgumentException("非代理商无权修改此配置!");
            }
            var result = this.vehicleTransportBusinessConfigOverwriteData.GetEntity(vehicleTransportBusinessConfigOverwriteId).Result;
            if (result == null)
            {
                throw new ArgumentException("车辆运输业务配置重写信息不存在");
            }
            result.Enabled = enabled;
            result.UpdateTime = DateTime.Now;
            result.EditAdminId = admin.AdminId;
            result.EditAdminName = admin.FullName;
            this.vehicleTransportBusinessConfigOverwriteData.Update(result).GetAwaiter().GetResult();
            this.redisService.DeleteMultipleKey(key, false);
            return result.As<VehicleTransportBusinessConfigOverwriteDto>();
        }
    }
}
